<?php

namespace core\middleware\uc;

use app\bll\UcenterMenu as BllUcenterMenu;
use support\View;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
use core\traits\Response as TraitsResponse;
use Exception;
use app\bll\SyscnfUcenter as BllSyscnfUcenter;

class AuthIntercept implements MiddlewareInterface
{
    use TraitsResponse;
    public function process(Request $request, callable $handler): Response
    {

        $controllers = explode('/', get_controller());

        $controller_group = strtolower(isset($controllers[0]) ? $controllers[0] : '');
        $controller_class = strtolower(isset($controllers[1]) ? $controllers[1] : '');

        $SyscnfUcenterinfo = [];
        if ($controller_group == 'uc') {
            $SyscnfUcenterinfo = $this->getUcConfig();
        }

        if (
            $controller_group == 'uc'
            && $controller_class != 'logreg'
        ) {

            if ($SyscnfUcenterinfo && $SyscnfUcenterinfo['enableuc'] == -1) {
                throw new Exception('用户中心未开放');
            }

            if (!request()->session()->get('userinfo')) {
                if (request()->isAjax()) {
                    return $this->error(
                        message: '请登录',
                        code: -999
                    );
                } else {
                    return redirect('/uc/Logreg/index');
                }
            }

            request()->userinfo = request()->session()->get('userinfo');
            $this->assignMenu();
        }


        return $handler($request);
    }

    /**
     * 渲染菜单
     *
     * @return void
     */
    private function assignMenu()
    {
        $bllUcenterMenu = new BllUcenterMenu();
        $nowurl         = get_now_url();
        $nowmenu        = $bllUcenterMenu->findByUrl($nowurl);
        if (!$nowmenu) {
            throw new Exception('地址不存在', 404);
        }
        //面包屑
        $crumb          = $bllUcenterMenu->getAncestorsAndSelf($nowmenu);
        if ($crumb[0]['type'] == 0) {
            $menutree      = $bllUcenterMenu->tree(type: 0);
            $firstMenuNode = $bllUcenterMenu->getNodeByTree($crumb[0]['ident'], $menutree);
            View::assign('firstMenuNode', $firstMenuNode);
        }
        View::assign('crumb', $crumb);
    }




    private function getUcConfig()
    {
        $bllSyscnfUcenter  = new BllSyscnfUcenter();
        $SyscnfUcenterinfo = $bllSyscnfUcenter->find();
        View::assign('SyscnfUcenterinfo', $SyscnfUcenterinfo);
        return $SyscnfUcenterinfo;
    }
}
